/* 公共 javascript 库，内包含一些有用的操作，
 * 要正常使用，网页需要加载 prototype.js frame
*/

/* 取得 XML Object 中 Tag 的值 */
function xml_getTagValue(xmlobj, tagname)
{
   return xmlobj.getElementsByTagName(tagname)[0].childNodes[0].nodeValue;
}

/* 生成 Select 表单项 */
function makeSelectOption(optionHash, selectedOption)
{
   var str = "";
   optionHash.each(function(pair) {
	  str += "<option value=\"" + pair.key + "\" ";
	  str += (selectedOption == pair.key) ? " selected=\"selected\" " : "";
	  str += ">" + pair.value + "</option>\n";
   });
   return str;
}

/* 判断是否闰年 */
function isLeapYear(year) {
   return y % 4 == 0 && (y % 400 == 0 || y % 100 != 0);
}

/* 生成日期的年选择框项 */
function makeOptionYear(select_id, start, end)
{
   var h = $H({});
   $R(start, end).each(function(item){
	  h.set(item, item);
   });
   $(select_id).update(makeSelectOption(h, end));
}

/* 生成日期的月选择框项 */
function makeOptionMonth(select_id)
{
   var h = $H({});
   $R(1, 12).each(function(item){
	  h.set(item, item);
   });
   $(select_id).update(makeSelectOption(h, 1));
}

/* 生成日期的日选择框项 */
function makeOptionDay(select_id, month, year)
{
   var month_day = {
	  1:31, 2:29, 3:31, 4:30, 5:31, 6:30,
		7:31, 8:31, 9:30, 10:31, 11:30, 12:31
   };
   var h = $H({});
   $R(1, month_day[month]).each(function(item){
	  h.set(item, item);
   });
   $(select_id).update(makeSelectOption(h, 1));
}

/* 获取选择框列表中的所有数据 */
function getValuesFromSelect(select_id)
{
   var a = [];
   $A($(select_id).getElementsByTagName("option")).each(function(item){
	  a[a.length] = {
		 "label": item.innerHTML,
		 "value": item.getAttribute("value")
		};
   });
   return a;
}

/* 数据是否存在于选择框/列表中 */
/* flag：0 代表按值搜索，1 代表按标签搜索 */
function existsInSelect(select_id, v, flag)
{
   var f = false;
   $A($(select_id).getElementsByTagName("option")).each(function(item){
	  switch(flag)
		{
		 case 1:
		   if (item.innerHTML == v)
			 {
				f = true;
				throw $break;
			 }
		   break;
		 case 0:
		   if (item.getAttribute("value") == v)
			 {
				f = true;
				throw $break;
			 }
		   break;
		 default:
		   window.alert("非法参数！");
		}
   });
   return f;
}

/* 解析单选框 */
function getRadioValue(name)
{
   var v = -1;
   $A(document.getElementsByName(name)).each(function(item) {
	  if (item.checked) v = $F(item);
   });
   return v;
}

/* 解析复选框 */
function getCheckboxValue(name)
{
   var a = [];
   $A(document.getElementsByName(name)).each(function(item){
	  if (item.checked) a[a.length] = $F(item);
   })
   return a;
}

/* 单选框值传递到文本框 */
function radio2text(rad, inp)
{
   rad.checked = "checked";
   inp.value = rad.value;
}


/* ----------- 分页 ----------- */
var Pager = Class.create();
Pager.prototype = {
   // 初始化对象
   initialize: function(total, page_span, obj_name, do_fun) {
	  this.total = total;
	  this.page_span = $(page_span);
	  this.obj_name = obj_name;
	  this.do_fun = do_fun;
   },
   // 更新数据总条数
   chTotal: function(total) {
	  this.total = total;
   },
   // 更新 Page 条
   chPage: function(page) {
	  eval((this.do_fun + "(" + page + ");"));
	  this.showPage(page);
   },
   // 显示 Page 条
   showPage: function(page) {
	  var str = "";
	  var options = $H({});
	  var r = $R(1, this.total);
	  var num = r.size();
	  r.each(function(i) {
		 options.set(i, (i + "/" + num));
	  });
	  str += " | ";
	  str += (page == 1) ? " 首页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(1);\">首页</a> ";
	  str += " | ";
	  str += (page == 1) ? " 上一页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(" + (parseInt(page, 10) - 1) + ");\">上一页</a> ";
	  str += " | ";
	  str += (page == this.total) ? " 下一页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(" + (parseInt(page, 10) + 1) + ");\">下一页</a> ";
	  str += " | ";
	  str += (page == this.total) ? " 末页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(" + this.total + ");\">末页</a> ";
	  str += " | ";
	  str += "&nbsp; &nbsp;";
	  str += " 页码： ";
	  str += "<select onchange=\"" + this.obj_name + ".chPage(this.value);\">";
	  str += makeSelectOption(options, page);
	  str += "</select>";
	  this.page_span.update(str);
   }
};

/* -------------  FCKEditor 操作函数  ------------- */
/* 加载 FCKeditor */
function show_FCKEditor(id, size)
{
   if (!size["width"])
     {
		size["width"] = "100%";
     }
   if (!size["height"])
     {
		size["height"] = "200";
     }
   var oEditor = new FCKeditor(id);
   oEditor.BasePath = "../fckeditor/";
   // oEditor.BasePath = "/oa/www/fckeditor/";
   oEditor.Width = size["width"];
   oEditor.Height = size["height"];
   oEditor.ReplaceTextarea();
}

/* 获取 FCKeditor 数据 */
function get_FCKData(id)
{
   var  oEditor = FCKeditorAPI.GetInstance(id);
   return oEditor.GetXHTML(true);
}

/* -------------- 数组操作 -------------- */
/* 检测数组中是否有相同的元素 */
/* 传入一个数组，如果有相同元素，则返回相同元素，如没有，则返回 false */
function checkArraySame(a)
{
   if (!a) { return false; }
   // 复制一份给新的数组，不然会修改原数组，因为 javascript 操作对象是引用方式
   // slice(start, end) 是截取函数，截取从 start 到 end 的元素到新数组中，
   // 省略 end 则表示截取到结尾
   var l = a.slice(0);
   l = l.sort();
   var temp;
   for (var i = 0; i < l.length; i ++)
     {
		if (temp != l[i]) temp = l[i];
		else return temp;
     }
   
   return false;
}

/* 数组到 Hash */
function array2hash(a)
{
   var h = {};
   for (var i = 0; i < a.length; i ++)
     {
		h["" + i] = a[i];
     }
   return h;
}

/* hash 到数组 */
function hash2array(h)
{
   var a = [];
   var aHash = $H(h);
   aHash.each(function(item){
      a[a.length] = item.value;
   });
   return a;
}

/* ------------ 模板分析处理 ------------ */
/* 分析表单类型模板的各项表单数据，返回处理后的表单代码 */
function getTplInput(name, type, sizeX, sizeY, options)
{
   var str = "";
   var width = (sizeX > 0) ? "width:" + sizeX + "px;" : "";
   var height = (sizeY > 0) ? "height:" + sizeY + "px;" : "";
   var style_X = " style=\"" + width + "\" ";
   var style_XY = " style=\"" + width + height + "\" ";
   var idname = " id=\"" + name + "\" name=\"" + name + "\"";
   switch (type)
	 {
	  case "t":
		str += "<input type=\"text\" " + idname + style_X + " value=\"" + options + "\" />";
		break;
	  case "l":
		str += "<input type=\"text\" " + idname + style_X + " value=\"" + options + "\" disabled=\"disabled\"/>";
		break;
	  case "a":
		str += "<textarea " + idname + style_XY + ">" + options + "</textarea>";
		break;
	  case "r":
		var names = " name=\"" + name + "[]\" ";
		var opt_items = options.split("|");
		for (var i = 0; i < opt_items.length; i ++)
		  {
			 var checked = (i == 0) ? " checked=\"checked\" " : "";
			 str += "<input type=\"radio\" id=\"" + name + "_" + i + "\" " + names + " value=\"" + opt_items[i] + "\" " + checked + " /> " + opt_items[i] + " ";
		  }
		break;
	  case "c":
		var names = " name=\"" + name + "[]\" ";
		var opt_items = options.split("|");
		for (var i = 0; i < opt_items.length; i ++)
		  {
			 str += "<input type=\"checkbox\" id=\"" + name + "_" + i + "\" " + names + " value=\"" + opt_items[i] + "\" /> " + opt_items[i] + " ";
		  }
		break;
	  case "p":
		str += "<input type=\"password\" " + idname + style_X + " value=\"" + options + "\" />";
		break;
	  case "s":
		var opt_items = options.split("|");
		str += "<select " + idname + style_X + ">";
		for (var i = 0; i < opt_items.length; i ++)
		  {
			 var selected = (i == 0) ? " selected=\"selected\" " : "";
			 str += "<option value=\"" + opt_items[i] + "\" " + selected + "> " + opt_items[i] + "</option>";
		  }
		str += "</select>";
		break;
	  default:
		str = "";
		break;
	 }
   return str;
}

/* ----------------------------------------------- */
/* 取得页面滚动位置 */
function getPageScroll()
{
   var yScroll;
   if (self.pageYOffset) 
	 {
		yScroll = self.pageYOffset;
	 }
   // Explorer 6 Strict
   else if (document.documentElement && document.documentElement.scrollTop)
	 {
		yScroll = document.documentElement.scrollTop;
	 }
   // all other Explorers
   else if (document.body)
	 {
		yScroll = document.body.scrollTop;
	 }
   
   arrayPageScroll = new Array('',yScroll);
   return arrayPageScroll;
}

/* 取得页面大小 */
function getPageSize(){  
   var xScroll, yScroll;  
   if (window.innerHeight && window.scrollMaxY) {  
	  xScroll = document.body.scrollWidth;
	  yScroll = window.innerHeight + window.scrollMaxY;
   } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
	  xScroll = document.body.scrollWidth;
	  yScroll = document.body.scrollHeight;
   } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
	  xScroll = document.body.offsetWidth;
	  yScroll = document.body.offsetHeight;
   }
   
   var windowWidth, windowHeight;
   if (self.innerHeight) {  // all except Explorer
	  windowWidth = self.innerWidth;
	  windowHeight = self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	  windowWidth = document.documentElement.clientWidth;
	  windowHeight = document.documentElement.clientHeight;
   } else if (document.body) { // other Explorers
	  windowWidth = document.body.clientWidth;
	  windowHeight = document.body.clientHeight;
   }  
   
   // for small pages with total height less then height of the viewport
   if(yScroll < windowHeight){
	  pageHeight = windowHeight;
   } else {
	  pageHeight = yScroll;
   }
   
   if(xScroll < windowWidth){  
	  pageWidth = windowWidth;
   } else {
	  pageWidth = xScroll;
   }
   
   arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
   return arrayPageSize;
}

/* ----------------------------------------- */
/* ----- 获取公司、部门、职位列表 ----- */
/* 获取公司 */
function getCompanyList(update_id, url, selected)
{
   var str = "";
   var myAjax = new Ajax.Request(url, {
	  asynchronous: false,
		onComplete: function(req)
		  {
			 var xmlobj = req.responseXML;
			 var companies = $A(xmlobj.getElementsByTagName("company"));
			 str += "<option value=\"-1\" selected=\"selected\">请选择公司...</option>";
			 companies.each(function(item){
				var item_id = item.getAttribute("id");
				var item_name = item.getAttribute("name");
				var s = (selected == item_id) ? " selected=\"selected\" " : "";
				str += "<option value=\"" + item_id + "\" " + s + ">" + item_name + "</option>\n";
			 });
		  }
   });
   $(update_id).update(str);
}
/* 获取部门 */
function getSectionList(update_id, url, v, selected)
{
   var str = "";
   var myAjax = new Ajax.Request(url, {
	  asynchronous: false,
		onComplete: function(req)
		  {
			 var xmlobj = req.responseXML;
			 var companies = xmlobj.getElementsByTagName("company");
			 var company;
			 str += "<option value=\"-1\" selected=\"selected\">请选择部门...</option>";
			 for (var i = 0; i < companies.length; i ++)
			   {
				  if (v == companies[i].getAttribute("id"))
					{
					   company = companies[i];
					}
			   }
			 var sections = $A(company.getElementsByTagName("section"));
			 sections.each(function(item){
				var item_id = item.getAttribute("id");
				var item_name = item.getAttribute("name");
				var s = (item_id == selected) ? " selected=\"selected\" " : "";
				str += "<option value=\"" + item_id + "\" " + s + ">" + item_name + "</option>\n";
			 });
		  }
   });
   $(update_id).update(str);
}
/* 获取职位 */
function getPositionList(update_id, url, v, selected)
{
   var str = "";
   var myAjax = new Ajax.Request(url, {
	  asynchronous: false,
		onComplete: function(req)
		  {
			 var xmlobj = req.responseXML;
			 var sections = xmlobj.getElementsByTagName("section");
			 var section;
			 str += "<option value=\"-1\" selected=\"selected\">请选择职位...</option>";
			 for (var i = 0; i < sections.length; i ++)
			   {
				  if (v == sections[i].getAttribute("id"))
					{
					   section = sections[i];
					}
			   }
			 var positions = $A(section.getElementsByTagName("position"));
			 positions.each(function(item){
				var item_id = item.getAttribute("id");
				var item_name = item.getAttribute("name");
				var s = (item_id == selected) ? " selected=\"selected\" " : "";
				str += "<option value=\"" + item_id + "\" " + s + ">" + item_name + "</option>\n";
			 });
		  }
   });
   $(update_id).update(str);
}
/* 获取用户列表，通过某一类型（公司？部门？职位？办公室？组？） */
function getUserList(update_id, url, t, v, selected, except)
{
   // t 值 ── "c":company, "s":section, "p":position, "o":office, "g":group
   var str = "";
   var pars = 
	 {
		"by": t,
		  "bv": v
	 };
   var myAjax = new Ajax.Request(url, {
	  asynchronous: false,
		method: "get",
		parameters: pars,
		onComplete: function(req)
		  {
			 var xmlobj = req.responseXML;
			 var users = $A(xmlobj.getElementsByTagName("user"));
			 str += "<option value=\"-1\" selected=\"selected\">请选择...</option>";
			 users.each(function(item){
				var item_id = item.getAttribute("id");
				var item_name = item.getAttribute("name");
				var s = (item_id == selected) ? " selected=\"selected\" " : "";
				str += (item_id != except) ? "<option value=\"" + item_id + "\" " + s + ">" + item_name + "</option>\n" : "";
			 });
		  }
   });
   $(update_id).update(str);
}

/* 获取元素在页面中的绝对位置 */
// 获取元素的纵坐标
function getElementTop(e){
   var offset=e.offsetTop;
   if(e.offsetParent!=null) offset+=getElementTop(e.offsetParent);
   return offset;
}
// 获取元素的横坐标
function getElementLeft(e)
{
   var offset=e.offsetLeft;
   if(e.offsetParent!=null) offset+=getElementLeft(e.offsetParent);
   return offset;
}
 

/* ---------------------------------------------------- */
/* 简单菜单生成函数 */
function makeSimpleMenu(goal, pars)
{
   var str = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n";
   $A(pars).each(function(item){
	  var i_onclick = item["onclick"];
	  var i_name = item["name"];
	  str += "<tr><td><a href=\"javascript:void(0);\" onclick=\"" + i_onclick + "\">" + i_name + "</a></td></tr>";	  
   });
   str += "</table>\n";
   $(goal).update(str);
}
